﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WeiXinPF.Common;
using System.Text;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using WeiXinPF.Model;
using System.Dynamic;
using System.IO;
using Newtonsoft.Json;

namespace WeiXinPF.Web.shop
{
    /// <summary>
    /// shopmgr 的摘要说明
    /// </summary>
    public class shopmgr : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            try
            {
                BLL.wx_shop_cart cartBll = new BLL.wx_shop_cart();
                string _action = MyCommFun.QueryString("myact");
                string openid = MyCommFun.RequestOpenid();
                Dictionary<string, string> jsonDict = new Dictionary<string, string>();
                if (_action == "addCart")
                {
                    #region 添加购物车
                    try
                    {
                        int wid = MyCommFun.RequestInt("wid");
                        int productId = MyCommFun.RequestInt("productid");
                        int skuId = MyCommFun.RequestInt("skuid");
                        string skuInfo = MyCommFun.QueryString("attr");
                        int productNum = MyCommFun.RequestInt("bc");
                        if (productNum == 0)
                        {
                            jsonDict.Add("errCode", "请选择需要购买的产品。");
                            return;
                        }
                        //TODO 从数据库中获取总价信息
                        BLL.wx_shop_product productService = new BLL.wx_shop_product();
                        var product = productService.GetModel(productId);
                        if (product == null)
                        {
                            jsonDict.Add("errCode", "无法找到该产品。");
                            return;
                        }
                        decimal totalPrice = (decimal)(product.salePrice);

                        //decimal totalPrice = (decimal)MyCommFun.RequestFloat("totprice", 0);
                        //类型，如exchange
                        string extraType = MyCommFun.QueryString("extratype");

                        Model.wx_shop_cart cart = new Model.wx_shop_cart();

                        IList<Model.wx_shop_cart> cartList = cartBll.GetModelList("productId=" + productId + " and openid='" + openid + "' and skuId=" + skuId);
                        bool isAdd = true;
                        if (cartList != null && cartList.Count > 0)
                        {
                            isAdd = false;
                            cart = cartList[0];
                        }
                        if (isAdd)
                        {
                            cart.createDate = DateTime.Now;
                            cart.openid = openid;
                            cart.productId = productId;
                            cart.productNum = productNum;
                            cart.skuId = skuId;
                            cart.skuInfo = skuInfo;
                            cart.totPrice = totalPrice * productNum;
                            cart.wid = wid;
                            int ret = cartBll.Add(cart);
                            if (ret > 0)
                            {
                                jsonDict.Add("errCode", "0");
                            }
                            else
                            {
                                jsonDict.Add("errCode", "1");
                            }
                        }
                        else
                        {
                            cart.openid = openid;

                            cart.productNum += productNum;
                            cart.skuId = skuId;
                            cart.skuInfo = skuInfo;
                            cart.totPrice += totalPrice * productNum;
                            cart.wid = wid;
                            bool ret = cartBll.Update(cart);
                            if (ret)
                            {
                                jsonDict.Add("errCode", "0");
                            }
                            else
                            {
                                jsonDict.Add("errCode", "1");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        jsonDict.Add("errCode", "因为：" + ex.Message);
                    }
                    finally
                    {
                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    }
                    #endregion
                }
                else if (_action == "pcount")
                {
                    #region 购物车商品数量
                    jsonDict = new Dictionary<string, string>();
                    int wid = MyCommFun.RequestInt("wid");
                    int count = cartBll.GetRecordCount("wid=" + wid + " and openid='" + openid + "'");
                    jsonDict.Add("data", count.ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    #endregion
                }
                else if (_action == "remove")
                {
                    #region 移除购物车商品
                    jsonDict = new Dictionary<string, string>();
                    int cartId = MyCommFun.RequestInt("id");
                    cartBll.Delete(cartId);
                    jsonDict.Add("errCode", "false");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    #endregion
                }
                else if (_action == "modifyNum")
                {
                    #region 修改购物车商品数量
                    jsonDict = new Dictionary<string, string>();
                    int cartId = MyCommFun.RequestInt("ic");
                    int newNum = MyCommFun.RequestInt("bc");
                    cartBll.UpdateNum(cartId, newNum);
                    jsonDict.Add("errCode", "false");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    #endregion
                }
                else if (_action == "getProvince")
                {
                    #region 获取省份列表
                    int sourid = MyCommFun.RequestInt("sourid");
                    BLL.pre_common_district areaBll = new BLL.pre_common_district();
                    IList<Model.pre_common_district> disList = areaBll.GetModelList("upid=" + sourid + " and level=1");
                    Model.pre_common_district dis;
                    StringBuilder jsonStr = new StringBuilder(
                        "{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                    for (int i = 0; i < disList.Count; i++)
                    {
                        dis = new Model.pre_common_district();
                        if (i != disList.Count - 1)
                        {
                            //TODO 可使用string.Format
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                        }
                        else
                        {
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                        }
                    }
                    jsonStr.Append("]}");
                    context.Response.Write(jsonStr);
                    #endregion
                }
                else if (_action == "getCity")
                {
                    #region 选择省份，改变城市列表
                    int privice = MyCommFun.RequestInt("pvid");
                    BLL.pre_common_district areaBll = new BLL.pre_common_district();
                    IList<Model.pre_common_district> disList = areaBll.GetModelList("upid=" + privice + " and level=2");
                    Model.pre_common_district dis;
                    //TODO 使用公用方法，生成返回的json字符串
                    //TODO 定义公用类，使用Newtonsoft.Serverlize方法
                    StringBuilder jsonStr = new StringBuilder(
                        "{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                    for (int i = 0; i < disList.Count; i++)
                    {
                        dis = new Model.pre_common_district();
                        if (i != disList.Count - 1)
                        {
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                        }
                        else
                        {
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                        }
                    }
                    jsonStr.Append("]}");
                    context.Response.Write(jsonStr);
                    #endregion
                }
                else if (_action == "getArea")
                {
                    #region 选择城市，改变区域列表
                    int ctid = MyCommFun.RequestInt("ctid");
                    BLL.pre_common_district areaBll = new BLL.pre_common_district();
                    IList<Model.pre_common_district> disList = areaBll.GetModelList("upid=" + ctid + " and level=3");
                    Model.pre_common_district dis;
                    StringBuilder jsonStr = new StringBuilder(
                        "{\"errCode\":0,\"retCode\":0,\"msgType\":0,\"errMsg\":\"\",\"data\":[");
                    for (int i = 0; i < disList.Count; i++)
                    {
                        dis = new Model.pre_common_district();
                        if (i != disList.Count - 1)
                        {
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"},");
                        }
                        else
                        {
                            jsonStr.Append("{\"id\":" + disList[i].id + ",\"name\":\"" + disList[i].name + "\"}");
                        }
                    }
                    jsonStr.Append("]}");
                    context.Response.Write(jsonStr);
                    #endregion
                }
                else if (_action == "order_save")
                {
                    #region 保存订单信息
                    //获得传参信息
                    int wid = MyCommFun.RequestInt("wid");
                    //支付方式：1货到付款；3微支付
                    int payment_id = MyCommFun.RequestInt("pc");
                    //物流方式
                    int express_id = MyCommFun.RequestInt("mtype");
                    // string orderStrList = MyCommFun.QueryString("orderStrList");

                    //检查物流方式
                    if (express_id == 0)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"对不起，请选择配送方式！\"}");
                        return;
                    }
                    BLL.wx_shop_user_addr uAddrBll = new BLL.wx_shop_user_addr();
                    IList<Model.wx_shop_user_addr> uaddrList = uAddrBll.GetOpenidAddrName(openid, wid);
                    if (uaddrList == null || uaddrList.Count <= 0 || uaddrList[0].id <= 0)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"收货地址不存在，无法结算！\"}");
                        return;
                    }

                    //检查购物车商品
                    IList<Model.cartProduct> cartListall = cartBll.GetCartList(openid, wid);
                    if (cartListall == null)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"对不起，购物车为空，无法结算！\"}");
                        return;
                    }
                    //购物车产品分类，积分和商城
                    IList<Model.cartProduct> cartList = new List<Model.cartProduct>();
                    IList<Model.cartProduct> cartList1 = new List<Model.cartProduct>();
                    var rewardCatalogID =
                    System.Configuration.ConfigurationManager.AppSettings["RewardProductCatalog"];
                    foreach (Model.cartProduct model_ in cartListall)
                    {
                        if (model_.catalogid != MyCommFun.Obj2Int(rewardCatalogID))
                        {
                            cartList.Add(model_);//价格表
                        }
                        else
                        {
                            cartList1.Add(model_);//积分表
                        }
                    }

                    //统计购物车
                    decimal payable_amount = cartList == null ? (decimal)0 : cartList.Sum(item => item.totPrice);
                    decimal alltotScore = cartList1 == null ? (decimal)0 : cartList1.Sum(item => item.totPrice);

                    //积分检查
                    int sid = 0;
                    BLL.wx_ucard_store storeBll = new BLL.wx_ucard_store();
                    IList<Model.wx_ucard_store> usList = storeBll.GetModelList(" wid='" + wid.ToString() + "' order by createDate desc,id desc");
                    if (usList != null && usList.Count > 0)
                    {
                        sid = usList[0].id;
                    }
                    BLL.wx_ucard_users userbll = new BLL.wx_ucard_users();
                    Model.wx_ucard_users usermodel = userbll.GetStoreUserInfo(openid, sid);
                    int ttscore = usermodel == null ? 0 : usermodel.ttScore;
                    if (ttscore - Convert.ToInt16(alltotScore) < 0)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"对不起，积分不足，无法结算！\"}");
                        return;
                    }
                    //库存余额验证
                    string stockerror = "";
                    foreach (Model.cartProduct p in cartListall)
                    {
                        if (p.stock < p.productNum) { stockerror += p.productName + "库存不足"; }
                    }
                    if (stockerror != string.Empty)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"" + stockerror + "\"}");
                        return;
                    }

                    //物流费用
                    BLL.express expressBll = new BLL.express();
                    Model.express expModel = expressBll.GetModel(express_id);
                    //支付方式
                    BLL.payment pbll = new BLL.payment();
                    Model.payment payModel = pbll.GetModelBypTypeId(payment_id);
                    //保存订单
                    Model.orders model = new Model.orders();
                    model.order_no = "b" + Utils.GetOrderNumber(); //订单号B开头为商品订单
                    model.order_no = Utils.CreateOrderNo("b");

                    //库存增减
                    BLL.wx_shop_product probll = new BLL.wx_shop_product();
                    foreach (Model.cartProduct p in cartListall)
                    {
                        probll.ReduceStock(p.productId, p.productNum);
                    }

                    //添加积分消费记录，并且进行减积分计算
                    if (usermodel != null)
                    {
                        BLL.wx_ucard_users_consumeinfo consumedll = new BLL.wx_ucard_users_consumeinfo();
                        Model.wx_ucard_users_consumeinfo conmod = new Model.wx_ucard_users_consumeinfo();
                        conmod.sId = sid;
                        conmod.uid = usermodel.id;
                        conmod.moduleType = "积分兑换";
                        conmod.moduleTypeId = 2;
                        conmod.moduleActionName = "积分兑换商品";
                        conmod.moduleActionId = 7;
                        conmod.cScoreType = 1;
                        conmod.score = Convert.ToInt16(-1 * alltotScore);
                        conmod.cMoneyType = 2;
                        conmod.consumeMoney = null;
                        conmod.addTime = DateTime.Now;
                        conmod.sort_id = 0;
                        conmod.pwd = "";
                        consumedll.Add(conmod, true);
                    }

                    model.wid = wid;
                    model.openid = openid;
                    model.modelName = "微商城";
                    model.modelCode = "shop";
                    model.modelActionName = "";
                    model.modelActionId = 0;
                    model.user_id = 0;
                    model.user_name = "";
                    model.payment_id = payment_id;
                    model.express_id = express_id;
                    model.accept_name = uaddrList[0].contractPerson;
                    model.post_code = "";
                    model.telphone = uaddrList[0].tel;
                    model.mobile = uaddrList[0].tel;
                    model.area = uaddrList[0].province;
                    model.city = uaddrList[0].city;
                    model.district = uaddrList[0].area;
                    model.address = uaddrList[0].province + " " + uaddrList[0].city + " " + uaddrList[0].area + " " + uaddrList[0].addrDetail;
                    model.message = "";
                    model.payable_amount = payable_amount;//应付商品总金额
                    model.real_amount = payable_amount;//实际商品总金额，
                    model.status = 1;
                    model.express_status = 1;
                    model.express_fee = expModel.express_fee; //物流费用

                    if (payment_id == 1)
                    {
                        //货到付款，需要确认订单
                        model.payment_status = 0; //标记未付款
                    }
                    else
                    {
                        //先款后货
                        model.payment_status = 1; //标记未付款
                    }
                    bool quicklyFH = false;
                    //如果是先款后货的话
                    if (payment_id == 3)
                    {
                        if (payModel.poundage_type == 1) //百分比
                        {
                            model.payment_fee = model.real_amount * payModel.poundage_amount / 100;
                        }
                        else //固定金额
                        {
                            model.payment_fee = payModel.poundage_amount;
                        }
                        BLL.wx_payment_wxpay wxBll = new BLL.wx_payment_wxpay();
                        Model.wx_payment_wxpay wxpay = wxBll.GetModelByWid(wid);
                        quicklyFH = wxpay.quicklyFH;
                    }
                    if (quicklyFH)
                    {
                        model.express_status = 0;
                    }
                    //订单总金额=实付商品金额+运费+支付手续费
                    model.order_amount = model.real_amount + model.express_fee + model.payment_fee;
                    //购物积分,可为负数
                    model.point = 0;
                    model.add_time = DateTime.Now;
                    //商品详细列表
                    List<Model.order_goods> gls = new List<Model.order_goods>();
                    foreach (Model.cartProduct item in cartList)
                    {
                        gls.Add(new Model.order_goods
                        {
                            goods_id = item.productId,
                            goods_title = item.productName,
                            goods_price = item.avgPrice,
                            real_price = item.avgPrice,
                            quantity = item.productNum,
                            point = 0
                        });
                    }
                    model.order_goods = gls;
                    int result = new BLL.orders().Add(model);
                    if (result < 1)
                    {
                        context.Response.Write("{\"errCode\":3, \"msg\":\"订单保存过程中发生错误，请重新提交！\"}");
                        return;
                    }

                    //清空购物车，此步骤移到确认支付页面
                    //提交成功，返回URL  order_no
                    context.Response.Write("{\"errCode\":true,\"payType\":\"" + payment_id + "\", \"order_no\":\"" + model.order_no + "\",\"orderid\":\"" + result + "\",\"wid\":\"" + wid + "\",\"openid\":\"" + openid + "\",\"payable_amount\":\"" + payable_amount + "\", \"msg\":\"恭喜您，订单已成功提交！\"}");
                    return;
                    #endregion
                }
                else if (_action == "order_canel")
                {
                    #region 取消订单
                    int orderid = MyCommFun.RequestInt("order_id");
                    BLL.orders oBll = new BLL.orders();
                    oBll.UpdateField(orderid, "status=4");
                    //TODO 取消订单需要把扣除的积分返还
                    context.Response.Write("{\"errCode\":true, \"msg\":\"订单已取消！\"}");
                    #endregion
                }
                else if (_action == "shouhuo")
                {
                    #region 确认收货
                    int orderid = MyCommFun.RequestInt("order_id");
                    BLL.orders oBll = new BLL.orders();
                    Model.orders order = oBll.GetModel(orderid);
                    if (order.payment_id == 1)
                    {
                        //货到付款
                        oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                    }
                    else
                    {
                        //在线支付
                        oBll.UpdateField(orderid, "express_status=2,payment_status=2 , status=3");
                    }

                    context.Response.Write("{\"errCode\":true, \"msg\":\"确认收货！\"}");
                    #endregion
                }
                else if (_action == "clearMyOrder")
                {
                    #region 清空我的购物车订单，在支付页面，支付成功后执行此功能
                    int wid = MyCommFun.RequestInt("wid");
                    cartBll.RemoveCartInfo(wid, openid);
                    #endregion
                }
                else if (_action == "product_comment_latest")
                {
                    #region 产品页面最新的三个产品评价
                    var productId = Convert.ToInt32(MyCommFun.QueryString("productid"));
                    var page = Convert.ToInt32(MyCommFun.QueryString("page"));
                    var pageSize = Convert.ToInt32(MyCommFun.QueryString("pagesize"));
                    var bll = new BLL.wx_shop_product_comment();
                    int totalCount = 0;
                    var comments = bll.GetApprovedCommentsByProductId(page,
                        pageSize, productId, AduitStatus.通过, out totalCount);
                    context.Response.Write(AjaxResult.Success(comments).ToCamelString());
                    #endregion
                }
                else if (_action == "product_comment_total")
                {
                    #region 获取所有评价数
                    var productId = Convert.ToInt32(MyCommFun.QueryString("productid"));
                    var bll = new BLL.wx_shop_product_comment();
                    var data = bll.GetProductCommentStatistics(productId);
                    if (data == null)
                    {
                        context.Response.Write(AjaxResult.Error(Constants.MessageContractAdministrator));
                        return;
                    }

                    context.Response.Write(AjaxResult.Success(data).ToCamelString());
                    #endregion
                }
                else if (_action == "product_comment_list")
                {
                    #region 根据类别获取产品分页评价列表
                    var productId = Convert.ToInt32(MyCommFun.QueryString("productid"));
                    var page = Convert.ToInt32(MyCommFun.QueryString("page"));
                    var pageSize = Convert.ToInt32(MyCommFun.QueryString("pagesize"));
                    var type = MyCommFun.QueryString("type");
                    RankLevel rank = RankLevel.全部;
                    //将type转化为RankLevel
                    //TODO 简单的做法
                    var lowerType = type.ToLower();
                    if (string.Equals(lowerType, "good"))
                    {
                        rank = RankLevel.好评;
                    }
                    else if (string.Equals(lowerType, "medium"))
                    {
                        rank = RankLevel.中评;
                    }
                    else if (string.Equals(lowerType, "negative"))
                    {
                        rank = RankLevel.差评;
                    }

                    var bll = new BLL.wx_shop_product_comment();
                    var totalCount = 0;
                    var comments = bll.GetCommentOnRankAndStatusByPage(page,
                        pageSize, productId, rank, AduitStatus.通过, out totalCount);
                    context.Response.Write(AjaxResult.Success(comments).ToCamelString());
                    #endregion
                }
                else if (_action == "product_evaluate")
                {
                    #region 评价产品
                    Stream postData = context.Request.InputStream;
                    StreamReader sRead = new StreamReader(postData);
                    string postContent = sRead.ReadToEnd();
                    sRead.Close();
                    var deserComment = JsonConvert.DeserializeObject<wx_shop_product_comment>(postContent);
                    if (deserComment == null)
                    {
                        context.Response.Write(AjaxResult.Error("评价参数异常"));
                        return;
                    }

                    if (new BLL.wx_shop_product_comment().Exists(deserComment.OrderId, deserComment.ProductId))
                    {
                        context.Response.Write(AjaxResult.Error("此产品已评价过"));
                        return;
                    }

                    Model.wx_shop_product_comment model = new wx_shop_product_comment();
                    model.ProductId = deserComment.ProductId;
                    //model.SkuId = skuid==string.Empty?0:deserComment.SkuId;
                    model.SkuId = deserComment.SkuId;
                    model.OrderId = deserComment.OrderId;
                    model.Content = deserComment.Content;
                    model.Score = deserComment.Score;
                    model.Rank = 7 - deserComment.Score / 2;
                    model.OpenId = openid;
                    model.Status = Model.AduitStatus.待审;
                    model.CreateTime = DateTime.Now;
                    model.Auditor = 0;
                    model.BusinessType = 0;
                    model.BusinessId = 0;
                    DataSet ds = new BLL.wx_crm_users().GetList(" wid = " + deserComment.wid + " and openid ='" + openid + "'");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        model.Username = ds.Tables[0].Rows[0]["nickname"].ToString();
                    }
                    new BLL.wx_shop_product_comment().SaveComment(model);
                    context.Response.Write(AjaxResult.Success("评价完成").ToCamelString());
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogEntry log = new LogEntry();
                log.Message = string.Format("Message:{0},StackTrace:{1}", ex.Message, ex.StackTrace);
                log.TimeStamp = DateTime.Now;
                log.Categories.Add(this.GetType().ToString());
                Logger.Write(log);

                context.Response.Write("{\"errCode\":3, \"msg\":\"操作失败，请联系管理员。\"}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}